<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="120px">
      <el-form-item label="微信手机号">
        <el-input
          v-model="queryParams.wxMobile"
          placeholder="请输入微信手机号码"
          maxlength="11"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号码"
          maxlength="11"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="充值日期">
        <el-date-picker
          v-model="queryParams.rechargeRangeDate"
          size="small"
          style="width: 240px"
          format="yyyy-MM-dd"
          value-format="timestamp"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleRechargeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="到期日期">
        <el-date-picker
          v-model="queryParams.endRangeDate"
          size="small"
          style="width: 240px"
          format="yyyy-MM-dd"
          value-format="timestamp"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="账号状态">
        <el-select style="width: 240px" v-model="queryParams.statue" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in statueOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户类型">
        <el-select style="width: 240px" v-model="queryParams.roleCode" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in roleCodeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="认证状态">
        <el-select style="width: 240px" v-model="queryParams.verifyCode" placeholder="请选择" clearable size="small">
          <el-option
            v-for="dict in certificationStatus"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-table
      border
      highlight-current-row
      v-loading="loading"
      :data="tableList"
      :row-key="getRowKeys"
      :expand-row-keys="expands"
      @expand-change="expandSelect"
    >
      <el-table-column label="展开" width="50" align="center" type="expand">
        <template slot-scope="{ row }">
          <el-table
            :border="false"
            :data="row.memberInfo"
            :header-cell-style="{ backgroundColor: '#fff', border: '0' }"
            :cell-style="{ border: '0' }"
          >
            <el-table-column
              v-for="(item, index) in recordTitles"
              :key="index"
              :label="item.title"
              :width="item.width"
              align="center"
            >
              <template slot-scope="{ row }">
                <template v-if="item.key == 'voucher'">
                  <el-popover v-if="row.voucher" placement="left" trigger="hover">
                    <el-image
                      slot="reference"
                      :src="row.voucher"
                      :alt="row.voucher"
                      style="max-height: 70px; max-width: 100px"
                    ></el-image>
                    <el-image :src="row.voucher" style="height: 500px; width: 500px"></el-image>
                  </el-popover>
                  <span v-else>---</span>
                </template>
                <template v-else>
                  <span>
                    {{ ((item.format ? item.format(row[item.key]) : row[item.key]) || item.default) | showTxt }}
                  </span>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column
        v-for="(item, index) in tableTitles"
        :key="index"
        :label="item.title"
        :width="item.width"
        align="center"
      >
        <template slot-scope="{ row }">
          <span>{{ ((item.format ? item.format(row[item.key]) : row[item.key]) || item.default) | showTxt }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <template v-if="row.rolesName == '超级会员'">
            <template v-if="row.statue == '禁用'">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['reviewActivities:memberManage:relieve']"
                @click="handleForbid(row, false)"
              >
                解禁
              </el-button>
            </template>

            <template v-else-if="row.statue == '到期'">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['reviewActivities:memberManage:renewal']"
                @click="handleRenewal(row)"
              >
                续约会员
              </el-button>
            </template>

            <template v-else>
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['reviewActivities:memberManage:edit']"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['reviewActivities:memberManage:forbid']"
                @click="handleForbid(row, true)"
              >
                禁用
              </el-button>
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['reviewActivities:memberManage:renewal']"
                @click="handleRenewal(row)"
              >
                续约会员
              </el-button>
            </template>
          </template>

          <template v-else>
            <el-button
              size="mini"
              type="text"
              v-hasPermi="['reviewActivities:memberManage:join']"
              @click="handleJoin(row)"
            >
              开通会员
            </el-button>
          </template>
          <!-- 身份认证相关 -->
          <el-dropdown trigger="click" v-if="row.verifyCode === 3" @command="(command) => {handleCommand(command, row);}">
            <span class="el-dropdown-link">身份认证</span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">查看认证</el-dropdown-item>
              <el-dropdown-item command="b">取消认证</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button size="mini" type="text" @click="handleAuthent(row)" v-else>
            <!-- {{ row.isVerified ? "取消认证" : "身份认证" }} -->
            身份认证
          </el-button>
          <el-button size="mini" type="text" @click="handleCooperation(row)">
            {{ row.canNotCooperation ? "解除禁止合作" : "禁止合作" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.currentPage"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog width="1000px" :title="operation" :visible.sync="showOptionPop" :close-on-click-modal="false">
      <memberOption
        :userInfo="currentUserInfo"
        :showOptionPop="showOptionPop"
        @togglePop="showOptionPop = false"
        @refresh="hanldeRefresh"
      ></memberOption>
    </el-dialog>

    <!-- 认证弹层 -->
    <el-dialog width="600px" :title="operation" :visible.sync="showAuthentPop" :close-on-click-modal="false">
      <authent-pop
        v-if="showAuthentPop"
        :userId="authentUserId"
        :type="authentType"
        :mobile="mobile"
        @onclose="showAuthentPop = false"
        @onrefresh="hanldeRefresh"
      ></authent-pop>
    </el-dialog>
  </div>
</template>

<script>
// <--会员管理-->
// reviewActivities/memberManage
import memberOption from "./com/memberOption";
import authentPop from "./authent-pop";
import {
  getMemberList,
  updateMemberInfo,
  userVerified,
  updateCanNotCooperation,
} from "@/api/reviewActivities/memberManage";
import { formatDateOnly, isSameDate } from "@/utils/index";
import { joinTypeMap } from "@/utils/config/member";

export default {
  name: "memberManage",
  components: {
    memberOption,
    authentPop,
    // certificationPop,
  },
  data() {
    return {
      expands: [],
      pickerOptions: {
        disabledDate: (time) => {
          const d = this.queryParams.rechargeRangeDate[0];
          if (d) {
            return d > time.getTime();
          }
          return false;
        },
      },
      currentUserInfo: {},
      showOptionPop: false, //会员相关的操作弹层
      showAuthentPop: false, //认证相关的操作弹层 ---线下认证
      showCertificationPpop: false, //认证相关的操作弹层 ---小程序端发起的认证
      authentUserId: "", //身份认证的当前用户
      authentType: '', //用来判断查看认证还是填写认证
      operation: "身份认证",
      loading: false,
      statueOptions: [
        { dictValue: "0", dictLabel: "正常" },
        { dictValue: "1", dictLabel: "禁用" },
        { dictValue: "2", dictLabel: "到期" },
      ],
      roleCodeOptions: [
        { dictValue: "commember", dictLabel: "普通用户" },
        { dictValue: "supermember", dictLabel: "超级会员" },
      ],
      certificationStatus: [
        { dictValue: "1", dictLabel: "未认证" },
        { dictValue: "2", dictLabel: "待审核" },
        { dictValue: "3", dictLabel: "认证通过" },
        { dictValue: "4", dictLabel: "认证未通过" },
      ],
      total: 0,
      // 查询参数
      queryParams: {
        currentPage: 1,
        pageSize: 10,
        rechargeRangeDate: [],
        endRangeDate: [],
        wxMobile: null,
        mobile: null,
        statue: null,
        roleCode: null,
        verifyCode: null,
      },
      tableTitles: [
        { title: "用户昵称", width: "150", key: "nickName" },
        { title: "用户真实姓名", width: "150", key: "realName" },
        { title: "微信手机号", width: "120", key: "wxMobile" },
        { title: "手机号", width: "120", key: "mobile" },
        {
          title: "用户类型",
          width: "100",
          key: "rolesName",
          default: "普通用户",
        },
        { title: "账号状态", width: "100", key: "statue", default: "正常" },
        {
          title: "认证状态",
          width: "100",
          key: "verifyCode",
          format(v) {
            if (v == 1) return "未认证";
            if (v == 2) return "待审核";
            if (v == 3) return "认证通过";
            if (v == 4) return "认证未通过";
          },
        },
        {
          title: "充值日期",
          width: "100",
          key: "rechargeDate",
          format: formatDateOnly,
        },
        {
          title: "会员到期日期",
          width: "100",
          key: "endDate",
          format: formatDateOnly,
        },
        {
          title: "最后操作时间",
          width: "100",
          key: "updateTime",
          format: formatDateOnly,
        },
      ],
      recordTitles: [
        { title: "序号", width: "100", key: "num" },
        { title: "类型", width: "100", key: "type" },
        { title: "开通类型", width: "100", key: "joinMemberType", format: (v) => joinTypeMap[v] },
        {
          title: "会员生效时间",
          width: "100",
          key: "startDate",
          format: formatDateOnly,
        },
        {
          title: "会员到期时间",
          width: "100",
          key: "endDate",
          format: formatDateOnly,
        },
        { title: "充值金额", width: "100", key: "amount", default: "0" },
        {
          title: "充值类型",
          width: "100",
          key: "rechargeType",
          default: "人工充值",
        },
        { title: "凭证", width: "100", key: "voucher" },
        {
          title: "推广人姓名",
          width: "100",
          key: "userName",
        },
        {
          title: "推广码",
          width: "100",
          key: "pushCode",
        },
        {
          title: "赠送原因",
          width: "100",
          key: "joinTypeReason",
        },
        {
          title: "创建时间",
          width: "100",
          key: "createTime",
          format: formatDateOnly,
        },
      ],
      tableList: [],
    };
  },
  filters: {
    showTxt(txt) {
      return txt ? txt : "--";
    },
    rounding(value) {
      return value.toFixed(2);
    },
  },

  computed: {},

  created() {
    this.handleQuery();
  },

  mounted() {},

  methods: {
    handleRechargeChange(value) {
      // console.log("充值时间", value);
      // if (!value) {
      //   // this.queryParams.rechargeRangeDate = []
      // }
    },
    getRowKeys(row) {
      return row.id;
    },

    expandSelect(row, expandedRows) {
      if (expandedRows.length) {
        this.expands = [];
        if (row) {
          this.expands.push(row.id);
        }
      } else {
        this.expands = [];
      }
    },
    handleEdit(info) {
      let memberInfoItem = info.memberInfo[0];
      if (memberInfoItem.parentId) {
        memberInfoItem = info.memberInfo.find((v) => v.id == memberInfoItem.parentId);
        if (!memberInfoItem) {
          return this.$message.error("未找到主订单！");
        }
      }

      if (memberInfoItem.rechargeType == "在线支付") {
        return this.$message.info("在线支付订单不可编辑！");
      }

      this.showOptionPop = true;
      this.operation = "编辑会员";

      this.currentUserInfo = {
        wxMobile: info.wxMobile,
        mobile: info.mobile,
        nickName: info.nickName,
        realName: info.realName,
        startDate: new Date(memberInfoItem.startDate),
        endDate: new Date(memberInfoItem.endDate),
        amount: memberInfoItem.amount,
        memberCode: "supermember",
        memberName: "超级会员",
        voucher: "",
        voucherUrl: memberInfoItem.voucher,
        id: memberInfoItem.id,
        agentId: info.agentId || info.id,
        operate: "update",
        rechargeType: memberInfoItem.rechargeType,
        joinMemberType: memberInfoItem.joinMemberType,
        pushCode: memberInfoItem.pushCode,
        cardType: memberInfoItem.cardType,
      };

      // console.log("handleEdit当前用户信息传入", {memberInfoItem});
    },

    handleRenewal(info) {
      this.showOptionPop = true;
      this.operation = "续约会员";
      const d = new Date();
      const memberInfoItem = info.memberInfo[0];
      const endD = new Date(memberInfoItem.endDate);
      let startDate;
      if (d.getTime() > memberInfoItem.endDate && !isSameDate(d, endD)) {
        startDate = d.getTime();
      } else {
        startDate = memberInfoItem.endDate + 1000 * 60 * 60 * 24;
      }

      this.currentUserInfo = {
        wxMobile: info.wxMobile,
        mobile: info.mobile,
        nickName: info.nickName,
        realName: info.realName,
        lastDate: formatDateOnly(memberInfoItem.endDate),
        startDate: new Date(startDate),
        endDate: "",
        memberCode: "supermember",
        memberName: "超级会员",
        voucher: "",
        voucherUrl: "",
        agentId: info.agentId || info.id,
        type: "1",
        operate: "add",
        pushCode: "",
        cardType: "",
      };
    },

    handleJoin(info) {
      this.showOptionPop = true;
      this.operation = "开通会员";
      this.currentUserInfo = {
        wxMobile: info.wxMobile,
        mobile: info.mobile,
        nickName: info.nickName,
        realName: info.realName,
        startDate: new Date(),
        endDate: "",
        amount: "",
        memberCode: "supermember",
        memberName: "超级会员",
        voucher: "",
        voucherUrl: "",
        agentId: info.agentId || info.id,
        type: "0",
        operate: "add",
        pushCode: "",
        cardType: "",
      };

      // console.log("当前用户信息传入", this.currentUserInfo);
    },

    // 身份认证 verifyCode  1未认证(线下认证)  2待审核(线上认证)  3取消认证
    handleAuthent(row) {
      if (row.verifyCode == 1) {
        this.showAuthentPop = true;
        this.operation = "身份认证";
        this.authentUserId = row.id;
        this.authentType = row.verifyCode,
        this.mobile = row.mobile
      } else if (row.verifyCode == 2||row.verifyCode == 4) {
        this.$router.push({ name: "CertificationPop", query: { userId: row.id,type:row.verifyCode } });
      } else if (row.verifyCode == 3) {
        this.cancelBut(row)
      }
    },
    handleCommand(command, row) {
      if (command == "a") {
        // offOnLine   1线上  2运营后台（线下）
        if (row.offOnLine == 1) {
          this.$router.push({ name: "CertificationPop", query: { userId: row.id,type:row.verifyCode } });
        } else if (row.offOnLine == 2) {
          this.showAuthentPop = true;
          this.operation = "身份认证";
          this.authentUserId = row.id;
          this.authentType = row.verifyCode
          this.mobile = row.mobile
        } else {
          this.$message({ type: "error", message: `无法判断是运营后台还是线上提交的通过完成`, duration: 2000 });
        }
      }
      if (command == "b") {
        this.cancelBut(row);
      }
    },
    // 取消认证
    cancelBut(row) {
      this.$confirm(`确定取消${row.nickName || row.realName || "无名"}的用户认证`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        userVerified({type: 2,userId: row.id,}).then(({ code }) => {
          if (code == 200) {
            this.$message({ type: "success", message: `取消认证成功！`, duration: 3000 });
            this.hanldeRefresh();
          } else {
            this.$message({ type: "error", message: `操作失败！`, duration: 3000 });
          }
        });
      });
    },

    // 禁止与否合作操作
    handleCooperation(row) {
      let name = row.nickName || row.realName;
      let tips = row.canNotCooperation ? `解除${name}的禁止合作？` : `确定${name}的禁止合作？`;

      this.$confirm(tips, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        updateCanNotCooperation({
          type: row.canNotCooperation ? 2 : 1,
          userId: row.id,
        }).then(({ code }) => {
          let tips = row.canNotCooperation ? "解除禁止成功！" : "禁止成功";
          if (code == 200) {
            this.$message({ type: "success", message: tips, duration: 3000 });
            this.hanldeRefresh();
          } else {
            this.$message({ type: "error", message: `操作失败！`, duration: 3000 });
          }
        });
      });
    },

    async handleForbid(info, isForbid) {
      const text = isForbid ? "禁用" : "解禁";
      await this.$confirm(`确定${text}：${info.nickName || info.wxMobile}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      });

      const { code } = await updateMemberInfo({
        id: info.agentId || info.id,
        statue: isForbid ? "1" : "0",
      });

      if (code == 200) {
        this.$message({
          type: "success",
          message: `${text}成功！`,
          duration: 3000,
        });

        this.handleQuery();
      }
    },

    //查询活动审核列表
    async getList({ page }) {
      this.loading = true;
      const rechargeRangeDate = this.queryParams.rechargeRangeDate || [];
      const endRangeDate = this.queryParams.endRangeDate || [];
      let queryData = {
        currentPage: page || this.queryParams.currentPage + 1,
        pageSize: this.queryParams.pageSize,
        t: {
          ...this.queryParams,
          rechargeMinDate: formatDateOnly(rechargeRangeDate[0]) || null,
          rechargeMaxDate: formatDateOnly(rechargeRangeDate[1]) || null,
          endMinDate: formatDateOnly(endRangeDate[0]) || null,
          endMaxDate: formatDateOnly(endRangeDate[1]) || null,
        },
      };

      const res = await getMemberList(queryData);
      const content = res.data.content;
      // const content = {total: 2, pages: list};

      this.queryParams.currentPage = queryData.currentPage;
      this.total = content.total;

      content.pages.forEach((item) => {
        let d = this.statueOptions.find((innerItem) => {
          return innerItem.dictValue == item.statue;
        });
        if (d) {
          item.statue = d.dictLabel;
        }

        let num = 1;
        item.memberInfo.forEach((item) => {
          item.num = num++;
          item.type = item.type == "0" ? "开通" : "续约";
        });
      });

      this.tableList = content.pages;

      this.loading = false;
    },

    // 搜索按钮操作
    handleQuery() {
      this.getList({ page: 1 });
    },

    hanldeRefresh() {
      this.showOptionPop = false;
      this.handleQuery();
    },
  },
};
</script>

<style>
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
}
</style>
